<template>
  <div class="user-info">
    <div class="left">
      <div>
        <img
          class="header-img"
          :src="userInfo.img"
          :onerror="errorImg"
          alt="头像"
          v-if="userInfo.img.indexOf('https://oss.i-town.cn/itown') != -1"
        />
        <img
          class="header-img"
          :src="http.ipAddress + userInfo.img"
          :onerror="errorImg"
          alt="头像"
          v-else
        />
        <div class="text">
          <p class="name">
            <span>{{ userInfo.userName }}</span>
          </p>
          <p class="date">
            <span>注册日期：{{ userInfo.createDate }}</span>
          </p>
          <p>
            <Button
              style="padding: 3px 16px"
              @click="modifyImg"
              type="info"
              size="small"
              ghost
              >修改头像</Button
            >
          </p>
        </div>
      </div>
      <Divider>
        <span icon="ios-settings">信息绑定</span>
      </Divider>
      <Card class="binding-group" shadow>
        <CellGroup>
          <Cell :title="'手机：' + (userInfo.phoneNo || '未绑定')">
            <Button
              type="success"
              size="small"
              @click="modifyPhone"
              icon="md-phone-portrait"
              slot="extra"
              >修改手机</Button
            >
          </Cell>
          <Cell :title="'邮箱：' + (userInfo.email || '未绑定')">
            <Button
              type="info"
              size="small"
              @click="modifyEmail"
              icon="ios-mail-outline"
              slot="extra"
              >绑定邮箱</Button
            >
          </Cell>
          <span v-if="showCode" class="showCode">
            <Button
              type="success"
              size="small"
              slot="extra"
              >{{isTrueCode ? '已绑定' : '未绑定'}}</Button
            >
            <Button
              type="info"
              size="small"
              @click="searchCode(1)"
              slot="extra"
              >绑定二维码</Button>
            <Button
              type="info"
              size="small"
              @click="searchCode(2)"
              slot="extra"
              >分销二维码</Button
            >
          </span>
          
        </CellGroup>
      </Card>
      <div style="padding: 17px">
        <Button type="error" @click="modifyPwd" size="large" icon="md-lock" long
          >修改密码</Button
        >
      </div>
    </div>
    <div class="right">
      <vol-form
        ref="form"
        :load-key="true"
        :width="500"
        :formRules="editFormOptions"
        :formFileds="editFormFileds"
      >
        <div slot="header">
          <Divider>
            <span class="ivu-icon ios-alert-outline">个人信息</span>
          </Divider>
          <span v-if="showCode" style="margin-top: 10px">
            <button> </button>
          </span>
        </div>
        <div slot="footer">
          <Button
            style="margin-top: 2px"
            type="info"
            size="large"
            icon="md-checkmark-circle"
            long
            @click="modifyInfo"
            >保存</Button
          >
        </div>
      </vol-form>
    </div>
    <VolBox
      :width="500"
      :height="260"
      :footer="false"
      :model.sync="modifyOptions.model"
      title="修改密码"
    >
      <div style="padding:10px;20px;">
        <VolForm
          ref="pwd"
          :formRules="modifyOptions.data"
          :formFileds="modifyOptions.fileds"
        >
        </VolForm>
        <Button type="info" size="large" icon="md-checkmark-circle" long @click="savePwd"
          >保存</Button
        >
      </div>
      <div slot="footer">
        <span></span>
      </div>
    </VolBox>
    <VolBox
      :width="500"
      :height="260"
      :footer="false"
      :model.sync="modifyOptionsImg.model"
      title="修改头像"
    >
      <div style="padding:10px;20px;">
        <VolForm
          ref="img"
          :formRules="modifyOptionsImg.data"
          :formFileds="modifyOptionsImg.fileds"
        >
        </VolForm>
        <Button type="info" size="large" icon="md-checkmark-circle" long @click="saveImg"
          >保存</Button
        >
      </div>
      <div slot="footer">
        <span></span>
      </div>
    </VolBox>
    <VolBox
      :width="500"
      :height="260"
      :footer="false"
      :model.sync="modifyOptionsPhone.model"
      title="修改手机号"
    >
      <div style="padding:10px;20px;">
        <VolForm
          ref="Phone"
          :formRules="modifyOptionsPhone.data"
          :formFileds="modifyOptionsPhone.fileds"
        ></VolForm>
        <Button
          type="info"
          size="large"
          icon="md-checkmark-circle"
          long
          @click="savePhone"
          >保存</Button
        >
      </div>
      <div slot="footer">
        <span></span>
      </div>
    </VolBox>
    <VolBox
      :width="500"
      :height="260"
      :footer="false"
      :model.sync="modifyOptionsEmail.model"
      title="修改邮箱"
    >
      <div style="padding:10px;20px;">
        <VolForm
          ref="Email"
          :formRules="modifyOptionsEmail.data"
          :formFileds="modifyOptionsEmail.fileds"
        ></VolForm>
        <Button
          type="info"
          size="large"
          icon="md-checkmark-circle"
          long
          @click="saveEmail"
          >保存</Button
        >
      </div>
      <div slot="footer">
        <span></span>
      </div>
    </VolBox>

    <VolBox 
      :model.sync="codeModel"
      title="二维码"
      :width="400"
      :height="300">
      <div class="codeBox" id="codeBox">
        <span v-if="showText">将二维码拷贝发给分销商，分销商扫码以后他的微信就绑定到该分销商，实现该分销商的在手机随时就能分享和提现。</span>
        <div v-if="showText">自己不要扫哦，一扫你就变成他的管理员了。</div>
        <div v-if="!showText" style="height: 20px"></div>
        <img :src="codeImg" alt="">
      </div>
      <div slot="footer">
        <Button type="success" @click="downloadIamge" icon="md-arrow-round-down"
          >下载</Button
        >
        <Button type="info" @click="codeModel = false" icon="md-close"
          >关闭</Button
        >
      </div>
    </VolBox>
  </div>
</template>
<script>
import VolForm from "@/components/basic/VolForm.vue";
export default {
  components: {
    VolForm: VolForm,
    VolBox: () => import("@/components/basic/VolBox.vue"),
  },
  methods: {
    modifyImg() {
      // this.$message.info("修改头像");
      this.$refs.img.reset();
      this.modifyOptionsImg.model = true;
    },
    saveImg() {
      if (!this.$refs.img.validate()) return;
      let url =
        "/api/user/modifyImg?newImg=" + this.modifyOptionsImg.fileds.newImg[0].path;

      this.http.post(url, {}, true).then((x) => {
        if (!x.status) {
          return this.$message.error(x.message);
        }
        this.getInfos();
        this.modifyOptionsImg.model = false;
        this.$Message.success(x.message);
        this.$refs.pwd.reset();
      });
    },
    modifyPhone() {
      this.$nextTick(() => {
        this.modifyOptionsPhone.fileds.phoneNo = this.userInfo.phoneNo;
      });

      this.$refs.Phone.reset();
      this.modifyOptionsPhone.model = true;
    },
    savePhone() {
      this.$refs.Phone.validate(() => {
        this.http
          .post(
            "/api/user/modifyPhone?newPhone=" + this.modifyOptionsPhone.fileds.newPhone,
            true
          )
          .then((x) => {
            if (!x.status) {
              return this.$message.error(x.message);
            }
            this.getInfos();
            this.modifyOptionsPhone.model = false;
            this.$Message.success("修改手机号成功");
          });
      });
    },
    modifyEmail() {
      this.$refs.Email.reset();
      this.modifyOptionsEmail.model = true;
      this.modifyOptionsEmail.fileds.email = this.userInfo.email;
    },
    saveEmail() {
      this.$refs.Email.validate(() => {
        this.http
          .post(
            "/api/user/modifyEmail?newEmail=" + this.modifyOptionsEmail.fileds.newEmail,
            true
          )
          .then((x) => {
            if (!x.status) {
              return this.$message.error(x.message);
            }
            this.getInfos();
            this.modifyOptionsEmail.model = false;
            this.$Message.success("修改邮箱成功");
          });
      });
    },
    getInfos() {
      this.http.post("/api/user/getCurrentUserInfo", {}, true).then((x) => {
        if (!x.status) {
          return this.$message(x.message);
        }
        x.data.createDate = (x.data.createDate || "").replace("T", " ");
        x.data.gender = x.data.gender + "";
        this.$refs.form.reset(x.data);
        // this.userInfo.img = this.base.getImgSrc(
        //   x.data.headImageUrl,
        //   this.http.ipAddress
        // );
        this.userInfo.img = x.data.headImageUrl || "";
        this.userInfo.createDate = x.data.createDate;
        this.userInfo.userName = x.data.userTrueName;
        this.userInfo.phoneNo = x.data.phoneNo;
        this.userInfo.email = x.data.email;
        //   this.editFormFileds = x.data;
      });
    },
    modifyPwd() {
      this.$refs.pwd.reset();
      this.modifyOptions.model = true;
    },
    savePwd() {
      if (!this.$refs.pwd.validate()) return;
      if (this.modifyOptions.fileds.newPwd != this.modifyOptions.fileds.newPwd1) {
        return this.$message.error("两次密码不一致");
      }
      let url =
        "/api/user/modifyPwd?oldPwd=" +
        this.modifyOptions.fileds.oldPwd +
        "&newPwd=" +
        this.modifyOptions.fileds.newPwd;
      this.http.post(url, {}, true).then((x) => {
        if (!x.status) {
          return this.$message.error(x.message);
        }
        this.modifyOptions.model = false;
        this.$Message.success(x.message);
        this.$refs.pwd.reset();
      });
    },
    modifyInfo() {
      this.$refs.form.validate(() => {
        this.http.post("/api/user/modifyUser", this.editFormFileds, true).then((x) => {
          this.getInfos();
          this.$Message.success("操作成功");
        });
      });
    },
    searchCode(flag) {
      if (sessionStorage.getItem("user")) {
        let user = JSON.parse(sessionStorage.getItem("user"));
        // 接口请求拿到二维码
        if (flag == 1) {
          this.showText = true;
          this.http.get(`/api/Users/GetBindAppUrl?UserId=${user.userId}`).then((res) => {
            if (res.status) {
              this.codeImg = res.data;
              this.codeModel = true;
            } else {
              this.codeImg = '';
              this.$Message.error(res.message)
            }
          })
        } else {
          this.showText = false;
          this.http.get(`/api/Users/GetProductAppUrl?UserId=${user.userId}`).then((res) => {
            if (res.status) {
              this.codeImg = res.data;
              this.codeModel = true;
            } else {
              this.codeImg = '';
              this.$Message.error(res.message)
            }
          })
        }
      } else {
        // 提示信息 请重新登录
        this.$message.error('请重新登陆')
      }
    },
    getCodeStatus() {
      if (sessionStorage.getItem("user")) {
        let user = JSON.parse(sessionStorage.getItem("user"));
        // 接口请求拿到二维码
        this.http.get(`/api/SmallUserArchives/GetUerIsBindApp?UserId=${user.userId}`).then((res) => {
          if (res.status) {
            this.isTrueCode = res.data;
          } else {
            this.$Message.error(res.message)
          }
        })
      } else {
        // 提示信息 请重新登录
        this.$message.error('请重新登陆')
      }
    },
    downloadIamge() {
      let ele = document.getElementById('codeBox');
      window.scrollTo(0, 0);
      let eleW = ele.offsetWidth; // 获得该容器的宽
      let eleH = ele.offsetHeight; // 获得该容器的高
      var canvas = document.createElement("canvas"); // 获得当前窗口的宽度（包含滚动条）
      canvas.width = eleW * 2; // 将画布宽&&高放大两倍
      canvas.height = eleH * 2;
      var context = canvas.getContext("2d");
      context.scale(2, 2);
      html2canvas(ele, {
        dpi: 300,
        scale: 1,
        // allowTaint: true,  //允许 canvas 污染， allowTaint参数要去掉，否则是无法通过toDataURL导出canvas数据的
        useCORS: true, //允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
        x: -2,
        y: -30,
      }).then((canvas) => {
        var oA = document.createElement("a");
        oA.download = '二维码' + ".jpg"; // 设置下载的文件名，默认是'下载'
        oA.href = canvas.toDataURL("image/jpeg");
        document.body.appendChild(oA);
        oA.click();
        oA.remove(); // 下载之后把创建的元素删除
      });
    }
  },
  created() {
    let user = JSON.parse(sessionStorage.getItem("user"));
    this.getInfos();
    this.showCode = user.code ? true : false;
  },
  mounted() {
    // 获取是否是分销得状态
    this.getCodeStatus();
  },
  data() {
    return {
      errorImg: 'this.src="' + require("@/assets/imgs/error-img.png") + '"',
      modifyOptions: {
        model: false,
        models: false,
        fileds: { oldPwd: "", newPwd: "", newPwd1: "" },
        data: [
          [
            {
              columnType: "string",
              required: true,
              title: "旧密码",
              field: "oldPwd",
            },
          ],
          [
            {
              type: "password",
              required: true,
              title: "新密码",
              field: "newPwd",
            },
          ],
          [
            {
              type: "password",
              required: true,
              title: "确认密码",
              field: "newPwd1",
            },
          ],
        ],
      },
      modifyOptionsImg: {
        model: false,
        fileds: { newImg: [] },
        data: [
          [
            {
              type: "img",
              required: true,
              title: "新头像",
              field: "newImg",
              url: "/api/user/Upload",
            },
          ],
        ],
      },
      modifyOptionsPhone: {
        model: false,
        fileds: { newPhone: "", phoneNo: "" },
        data: [
          [
            {
              type: "phone",
              title: "旧手机号",
              field: "phoneNo",
              disabled: true,
            },
          ],
          [
            {
              type: "phone",
              required: true,
              title: "新手机号",
              field: "newPhone",
            },
          ],
        ],
      },
      modifyOptionsEmail: {
        model: false,
        fileds: { newEmail: "", email: "" },
        data: [
          [
            {
              type: "email",
              title: "旧邮箱号",
              field: "email",
              disabled: true,
            },
          ],

          [
            {
              type: "email",
              required: true,
              title: "新邮箱号",
              field: "newEmail",
            },
          ],
        ],
      },
      binging: [{}],
      userInfo: {
        img: "",
        createDate: "--",
        userName: "--",
        email: "",
        phoneNo: "",
      },
      editFormFileds: {
        roleName: "",
        userName: "",
        userTrueName: "",
        address: "",
        gender: "",
        remark: "",
      },
      editFormOptions: [
        [
          {
            columnType: "string",
            title: "用户名",
            field: "userName",
            disabled: true,
          },
        ],
        [
          {
            columnType: "string",
            title: "角色",
            field: "roleName",
            disabled: true,
            type: "text",
          },
        ],
        [
          {
            columnType: "string",
            title: "真实姓名",
            field: "userTrueName",
            required: true,
            type: "text",
          },
        ],
        [
          {
            columnType: "string",
            title: "地址",
            field: "address",
            type: "text",
          },
        ],
        [
          {
            dataKey: "gender",
            title: "性别",
            field: "gender",
            data: [],
            type: "select",
          },
        ],
        [
          {
            columnType: "string",
            title: "备注",
            field: "remark",
            colSize: 12,
            type: "textarea",
          },
        ],
      ],
      codeModel: false,
      codeImg: '',
      showCode: false,
      isTrueCode: false,
      showText: true,
    };
  },
};
</script>
<style scoped>
.binding-group {
  width: 100%;
  padding-bottom: 20px;
}
.binding-group >>> .ivu-cell-link {
  text-align: left;
}
.binding-group >>> .ivu-card-body {
  padding: 0 16px;
}
.binding-group >>> .ivu-cell-title {
  line-height: 24px;
  font-size: 12px;
}
</style>

<style lang="less" scoped>
img[src=""],
img:not([src]) {
  opacity: 0;
}
.user-info {
  box-shadow: rgb(214, 214, 214) 0px 4px 21px;
  position: absolute;
  transform: translateY(-40%);
  top: 15%;
  position: relative;
  margin: 0 auto;
  left: 0;
  width: 895px;
  right: 0;
  text-align: center;
  padding: 0px;
  //display: flex;
  .text {
    padding: 5px;
    .name {
      font-weight: bolder;
      font-size: 15px;
      font-weight: 900;
    }
    > p {
      padding-top: 5px;
    }
  }
  .header-img {
    height: 150px;
    width: 150px;
    border-radius: 50%;
    margin-right: 0px;
    top: 4px;
    position: relative;
    border: 3px solid #dfdfdf;
  }
  > div {
    float: left;
    // height: 480px;
    padding-top: 10px;
  }
  .left {
    width: 320px;
    border-right: 1px solid #eee;
    // box-shadow: #d6d6d6 7px 4px 20px;
    // flex: 1;
  }
  .right {
    padding-left: 30px;
    width: 570px;
    // background: #fefefe;
    // flex: 3;
  }
}
.codeBox {
  display: flex;
  flex-direction: column;
  align-items:center;
  span {
    font-weight: 600;
    font-size: 14px;
  }
  div {
    color: red;
  }
  img {
    display: block;
    width: 200px;
    height: 200px;
  }
}
.showCode{
  display: flex;
  justify-content: space-around;
  margin-top: 5px;
}
</style>
